package com.lemon.smartsafety.ui.activity.fire.item.safemanage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.SafeManageDetails;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.activity.fire.item.inspection.FirefightingCompanyAddressActivity;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.rengwuxian.materialedittext.MaterialEditText;

import butterknife.Bind;
import cn.finalteam.galleryfinal.model.PhotoInfo;

public class FireSafeManageShowActivity extends PhotoSelectBaseActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.txt_title)
    TextView txtTitle;
    @Bind(R.id.lineAll)
    LinearLayout lineAll;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.metLastCheck)
    MaterialEditText metLastCheck;
    @Bind(R.id.metResultSelect)
    MaterialEditText metResultSelect;
    @Bind(R.id.rowResultSelect)
    TableRow rowResultSelect;
    @Bind(R.id.metRemark)
    MaterialEditText metRemark;
    @Bind(R.id.tl_basic_info)
    TableLayout tlBasicInfo;
    @Bind(R.id.iv_photo1)
    ImageView ivPhoto1;
    @Bind(R.id.iv_photo2)
    ImageView ivPhoto2;
    @Bind(R.id.iv_photo3)
    ImageView ivPhoto3;
    @Bind(R.id.rowPhotoOld)
    TableRow rowPhotoOld;
    @Bind(R.id.mainContainer)
    LinearLayout mainContainer;
    @Bind(R.id.txt_photo)
    TextView txtPhoto;
    @Bind(R.id.metRemarkHint)
    MaterialEditText metRemarkHint;
    @Bind(R.id.metPeriod)
    MaterialEditText metPeriod;


    private SafeManageDetails safeManageDetails;
    private SuperviseCompanyResult.ResultEntity resultEntity;
    public Intent intent;
    public Bundle bundle;
    public Activity mActivity;
    public LocationUtil locationUtil;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
            safeManageDetails = (SafeManageDetails) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_SAFE_BASE_INFO);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fire_safe_manage_show;
    }

    @Override
    protected void initViews() {
        super.initViews();
        FirefightingUtil.fireInspectAdd(FireSafeManageShowActivity.this);
        setShowAdd(false);
        mActivity=this;
        try {
            locationUtil = new LocationUtil(mActivity);
            ToastUtil.init(mActivity);
            ToastUtil.showShort();
        } catch (Exception e) {
            e.printStackTrace();
        }

        initEditView();

    }


    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.safe_manager_prop);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_inspection, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_fire_inspection) {
            //现场检查
            LogUtils.LOGE("现场检查");
            //点击现场检查
            locationUtil.getLoacation(new LocationUtil.CallBackInterface() {
                @Override
                public void callBackFunction() {
                    LogUtils.LOGE("定位地理位置");
                    signHttp();
                }
            });

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(FireSafeManageShowActivity.class);
    }


    @Override
    protected void initListener() {
        super.initListener();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHUDUtil.hidden();
    }

    private void initEditView() {
        if (null == safeManageDetails) return;
        if (null == resultEntity) return;

        txtTitle.setText(resultEntity.getCompanyName());

        tvTitle.setText(StringUtils.nullValue(safeManageDetails.getItem_name(), ""));
        metRemark.setText(String.format("%s", StringUtils.nullValue(safeManageDetails.getRecord_remark(), "--")));
        metLastCheck.setText(String.format("%s %s", StringUtils.nullValue(safeManageDetails.getLast_check_user(), "--"), DateUtils.getFormatDateStringWithDateString(safeManageDetails.getLast_check_time(), DateUtils.dateFormatYMDHM)));

        String lastResult = StringUtils.nullValue(safeManageDetails.getCheck_result(), "--");
        if (lastResult.indexOf(",") != -1) {
            lastResult = lastResult.substring(lastResult.indexOf(",") + 1);
        }

        metResultSelect.setText(lastResult);


        if (StringUtils.nullValue(safeManageDetails.getPicture1()).length() != 0) {
            final String url = HttpUtils.formatFilesUrl(safeManageDetails.getPicture1());
            ivPhoto1.setVisibility(View.VISIBLE);
            ivPhoto1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhotoInfo info = new PhotoInfo();
                    info.setPhotoPath(url);
                    UIHelper.showPhotoView(FireSafeManageShowActivity.this, info);
                }
            });
            GlideImageLoader.loadImage(this, url, ivPhoto1);
        } else {
            ivPhoto1.setVisibility(View.GONE);
            txtPhoto.setVisibility(View.GONE);
        }

        if (StringUtils.nullValue(safeManageDetails.getPicture2()).length() != 0) {
            final String url = HttpUtils.formatFilesUrl(safeManageDetails.getPicture2());
            ivPhoto2.setVisibility(View.VISIBLE);
            ivPhoto2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhotoInfo info = new PhotoInfo();
                    info.setPhotoPath(url);
                    UIHelper.showPhotoView(FireSafeManageShowActivity.this, info);
                }
            });
            GlideImageLoader.loadImage(this, url, ivPhoto2);
        } else {
            ivPhoto2.setVisibility(View.GONE);
        }

        if (StringUtils.nullValue(safeManageDetails.getPicture3()).length() != 0) {
            final String url = HttpUtils.formatFilesUrl(safeManageDetails.getPicture3());
            ivPhoto3.setVisibility(View.VISIBLE);
            ivPhoto3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhotoInfo info = new PhotoInfo();
                    info.setPhotoPath(url);
                    UIHelper.showPhotoView(FireSafeManageShowActivity.this, info);
                }
            });
            GlideImageLoader.loadImage(this, url, ivPhoto3);
        } else {
            ivPhoto3.setVisibility(View.GONE);
        }

        if (!CommonUtil.strIsEmpty(safeManageDetails.getRemark())) {
            metRemarkHint.setText(safeManageDetails.getRemark());
        }

        if (!CommonUtil.strIsEmpty(safeManageDetails.getCheck_freq() + safeManageDetails.getCheck_freq_unit_name())) {
            metPeriod.setText(safeManageDetails.getCheck_freq() + safeManageDetails.getCheck_freq_unit_name());
        }

    }


    /**
     * 监督签到 是否允许现场检查
     */
    public void signHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("latitude", locationUtil.getmLat());
        params.put("longitude", locationUtil.getmLng());
        params.put("position", locationUtil.getmAddress());

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Sign_in), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                            bundle.putSerializable(BundleKey.FIRE_COMPANY_SAFE_BASE_INFO, safeManageDetails);
                            UIHelper.showActivity(FireSafeManageShowActivity.this, bundle, FireSafeManageAddActivity.class);
                        } else {
                            if (baseMode.getCode().equals("2000")) {
                                openCompanyAddress(baseMode);
                            } else {
                                ToastUtil.show(baseMode.getMsg());
                            }
                        }
                    }
                }
            }
        });

    }


    /**
     * 提示用户完善定位信息
     * @param baseMode
     */
    private void openCompanyAddress(BaseMode baseMode) {

        getConfirmDialog(baseMode.getMsg(), R.string.fire_location_sure, R.string.fire_location_cancel, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    //添加
                    Intent intent = new Intent(mActivity, FirefightingCompanyAddressActivity.class);
                    bundle = new Bundle();
                    bundle.putSerializable(BundleKey.FIRE_COMPANY_BASE_INFO, resultEntity);
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            }
        }).show();
    }
}
